$NG.AllReady(function (page, { useAction, useBeforeClick, useValuesChange, useClick, useUpdateRow, subscribe, useUpdateRows }) {
    const mstform = $NG.getCmpApi("p_form_xmch_m")
    let dgrid1 = $NG.getCmpApi("p_form_xmch_d1")
    const toolbar = $NG.getCmpApi("toolbar")
    const toolbar_top = $NG.getCmpApi("toolbar_top")
    const getHeadValue = (str) => mstform.getItem(str).getValue()

    const config = {
        save_lock: true
    }
    try {
        isTabs()
    } catch (err) { }

    if (page.oType == 'add') {
        getIsOne()
        getCntCount("p_form_xmch_m", "u_htmc", "u_xmmc", () => { })
    }
    console.log(`page.isList`, page.isList);
    if (page.isList) {
        toolbar.insert({
            id: "open-gctzch",
            text: "过程调整策划记录",
            iconCls: "icon-New"
        });
    } else {
        toolbar_top.insert({
            id: "open-gctzch",
            text: "过程调整策划记录",
            iconCls: "icon-New"
        });

        toolbar_top.insert({
            id: "add-gctzch",
            text: "新增调整策划记录",
            iconCls: "icon-New"
        });
    }

    useClick(() => {
        openNGSingleHelp()
    }, "open-gctzch")

    useClick(() => {
        let phid = null
        let hash = null
        if (mstform.getValues().app_status == '0') {
            $NG.alert("单据未审核！")
            return
        }
        if (page.oType == 'add') {
            // const hash = '/react/index.html?v=1756178746778#/customform/detail?otype=add&busType=gctzch&isSso=0&AppTitle=%E8%BF%87%E7%A8%8B%E8%B0%83%E6%95%B4%E7%AD%96%E5%88%92-%E6%96%B0%E5%A2%9E&schemeId=6870000000000265&orgId=1&orgName=%E4%B8%AD%E5%9B%BD%E6%B0%B4%E5%88%A9%E6%B0%B4%E7%94%B5%E7%AC%AC%E5%85%AD%E5%B7%A5%E7%A8%8B%E5%B1%80%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8&menucode=5fc436eb-1eb8-89cb-159f-cb48449d2aaa'
            // const origin = location.origin
            // $NG.open(origin + hash)
            $NG.alert("当前不可调整！")
            return false
        } else {
            phid = mstform.getValues().phid
            if (!phid) {
                $NG.alert("发生异常！")
                return
            }
            $NG.execServer("SELECT", { sql: `select phid from p_form_gctzch_m where u_lyid='${phid}' and app_status=0` }, (res) => {
                console.log(`res`, res);
                if (res.count == 0) {
                    const hash = `/react/index.html?v=1756178746778#/customform/detail?sourceid=${phid}&otype=add&busType=gctzch&isSso=0&AppTitle=%E8%BF%87%E7%A8%8B%E8%B0%83%E6%95%B4%E7%AD%96%E5%88%92-%E6%96%B0%E5%A2%9E&schemeId=6870000000000265&orgId=1&orgName=%E4%B8%AD%E5%9B%BD%E6%B0%B4%E5%88%A9%E6%B0%B4%E7%94%B5%E7%AC%AC%E5%85%AD%E5%B7%A5%E7%A8%8B%E5%B1%80%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8&menucode=5fc436eb-1eb8-89cb-159f-cb48449d2aaa`
                    const origin = location.origin
                    $NG.open(origin + hash)
                } else {
                    const pd = JSON.parse(res.data)[0].extendObjects.phid
                    const hash = `/react/index.html?v=1756178746778#/customform/detail?id=${pd}&otype=edit&busType=gctzch&isSso=0&AppTitle=%e8%bf%87%e7%a8%8b%e8%b0%83%e6%95%b4%e7%ad%96%e5%88%92-%e4%bf%ae%e6%94%b9&schemeId=6870000000000265&orgId=1&orgName=%E4%B8%AD%E5%9B%BD%E6%B0%B4%E5%88%A9%E6%B0%B4%E7%94%B5%E7%AC%AC%E5%85%AD%E5%B7%A5%E7%A8%8B%E5%B1%80%E6%9C%89%E9%99%90%E5%85%AC%E5%8F%B8&menucode=5fc436eb-1eb8-89cb-159f-cb48449d2aaa`
                    const origin = location.origin
                    $NG.open(origin + hash)
                }

            })

        }

    }, "add-gctzch")

    useBeforeClick(() => {
        if (!config.save_lock) {
            $NG.alert("当前标段已含有一张项目策划单，请勿重复添加！")
            return false
        }
    }, "save")

    useValuesChange(() => {
        isTabs()
        if (page.oType == 'add') {
            getProjectChDetail()
        }
    }, "p_form_xmch_m.u_chzt")

    useValuesChange(() => {
        getProjectInfo()
        getIsOne()
        getCntCount("p_form_xmch_m", "u_htmc", "u_xmmc", () => { })
    }, "p_form_xmch_m.u_xmmc")

    useValuesChange(() => {
        getIsOne()
    }, "p_form_xmch_m.u_chzt")

    useUpdateRow(() => {
        sumAmt()
    }, "p_form_xmch_d1")

    function isTabs() {
        const bo = mstform.getItem("u_chzt").getValue()
        if (bo == '01') {
            selectTabs("tabPanel_tabItem")
        } else {
            selectTabs(1)
        }
        setTimeout(() => {
            dgrid1 = $NG.getCmpApi("p_form_xmch_d1")
        }, 200)
    }

    // 打开单选帮助
    function openNGSingleHelp() {
        let phid = null
        if (!page.isList) {
            phid = mstform.getValues().phid
        } else {
            const row = $NG.getCmpApi('grid').getSelectedData();
            if (row.length > 1 || row.length == 0) {
                $NG.alert("请选中一行数据！")
                return false
            }
            phid = row[0].phid
        }
        if (!phid) {
            $NG.alert("当前单据目前没有任何记录!")
            return
        }
        //自定义打开帮助
        $NG.external.openNGHelp({
            type: "NGSingleHelp",//NGSingleHelp
            helpId: "gctzch",
            valueField: "phid",
            labelField: "u_chmc",
            clientSqlFilter: `u_lyid = '${phid}'`
        }).then((data) => {
            console.log(data)
            //data:拿到帮助选中的数据
        })
    }

    // 获取但合同信息
    function getCntCount(form, key, phid_pc_key, fun) {
        const mst = $NG.getCmpApi(form)
        const phid_pc = mst.getItem(phid_pc_key || "phid_pc").getValue()
        if (!phid_pc) return
        $NG.execServer("getCntCount", { phid_pc }, (res) => {
            if (res.count == 1) {
                const data = JSON.parse(res.data)[0].extendObjects
                mst.getItem(key).setValue({
                    label: data.bill_name,
                    value: data.phid
                })
                fun()
            }

        })
    }

    // 获取单据
    function getIsOne() {
        const u_chzt = getHeadValue("u_chzt")
        const phid = mstform.getItem("u_xmmc").getValue()
        if (!phid || !u_chzt) return
        $NG.execServer("SELECT", { sql: `select phid from p_form_xmch_m where u_xmmc = '${phid}' and u_chzt = '${u_chzt}'` }, (res) => {
            if (res.count == 0) {
                config.save_lock = true
                $NG.message("单据唯一，当前可保存！")
            } else {
                config.save_lock = false
                $NG.alert("当前标段已含有一张项目策划单，请勿重复添加！")
            }
        })
    }

    // 标题编辑
    function sumAmt() {
        const rows = dgrid1.getRows()
        let yysr = 0 // %营业收入
        let gsglf = 0 // %公司管理费用
        let fjglf = 0 // %公司管理费用
        let cscbje = 0 // %成本测算费用
        // 汇总子明细到父节点
        childReduceTree(rows)
        rows.forEach(item => {
            switch (item.s_tree_name) {
                case '营业收入':
                    yysr += (Number(item.u_je) || 0)
                    break;
                case '成本测算':
                    cscbje += (Number(item.u_je) || 0)
                    break;
                case '公司':
                    gsglf += (Number(item.u_je) || 0)
                    break;
                case '分局':
                    fjglf += (Number(item.u_je) || 0)
                    break
            }
        })
        $NG.updateState((updater) => {
            updater.data.p_form_xmch_m.setProps({
                u_yysrbbyj: yysr,
                u_zcb: cscbje,
                u_gsglf: yysr != 0 ? (gsglf / yysr) : 0,
                u_fjglf: yysr != 0 ? (fjglf / yysr) : 0,
                u_lrl: yysr != 0 ? (yysr - cscbje) / yysr : 0,
                u_sfks: (yysr != 0 ? ((yysr - cscbje) / yysr) : 0) <= 0 ? '01' : '02'
            })
        })
        dgrid1.refreshView()
    }

    // 汇总明细金额到父节点方法
    function childReduceTree(item) {
        if (Array.isArray(item)) {
            item.forEach(el => {
                if (!el.s_tree_pid || el.s_tree_pid.length < 3) {
                    el.u_je = childReduceTree(el)
                }
            })
            return item
        }
        let total_amt = 0
        if (item.children && item.children.length > 0) {
            item.children.forEach(el => {
                el.u_je = childReduceTree(el)
                total_amt += childReduceTree(el)
            })
            return total_amt
        } else {
            return (Number(item.u_je) || 0)
        }
    }

    // 显示隐藏Tab页签
    function selectTabs(key) {
        const tabs = $NG
            .getCompMap()
            .get("__Tabs__")[0]
            .getApi();

        tabs.updateItems((innerItems, activeKey) => {
            return [...innerItems.filter((item) => {
                if (item.name == key) {
                    return item
                }
            })];
        });

        tabs.setActiveKey(key);
    }

    // 获取项目信息
    function getProjectInfo() {
        const phid = mstform.getItem("u_xmmc").getValue()
        if (!phid) return
        $NG.execServer("getProjectInfoByPhid", { phid }, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data)[0].extendObjects
            $NG.updateState((updater) => {
                updater.data.p_form_xmch_m.setProps({
                    u_htqdrq: datas.user_htqdrj,
                    u_zbrq: datas.user_zbrq,
                    u_htje: datas.approx_contract_fc,
                    u_htrq: datas.limit_time
                })
            })

        })
    }
    // 获取基础表信息
    function getProjectChDetail() {
        $NG.execServer("getProjectChDetail", {}, (res) => {
            if (res.count == 0) return
            const datas = JSON.parse(res.data).reduce((value, item) => {
                value.push(item.extendObjects)
                return value
            }, [])
            setTimeout(() => {
                const dgrid1 = $NG.getCmpApi("p_form_xmch_d1")
                const arr = arrayToTree(datas, "s_tree_id", "s_tree_pid")
                console.log(`添加的数据`, arr, datas);
                $NG.updateState((updater) => {
                    updater.data.p_form_xmch_d1.setProps(p => {
                        return arr
                    })
                })
                $NG.updateUI(updater => updater.grid.p_form_xmch_d1.s_tree_no.setProps(p => { return { ...p, levelSumary: true } }));
            }, 200)
        })
    }

    // 转属性结构
    function arrayToTree(items, idField = "id", parentField = "parentId", childrenField = "children") {
        const map = {};
        const roots = [];

        // 先建立 id → item 的映射
        items.forEach(item => {
            map[item[idField]] = { ...item, [childrenField]: [] };
        });

        // 组装树
        items.forEach(item => {
            const parentId = item[parentField];
            if (parentId == null || parentId.length < 2 || parentField == '0') {
                // 根节点
                roots.push(map[item[idField]]);
            } else if (map[parentId]) {
                // 挂到父节点的 children 上
                map[parentId][childrenField].push(map[item[idField]]);
            }
        });

        return roots;
    }
})